package com.yusp75.myexam.ui.home

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.yusp75.myexam.com.yusp75.myexam.data.BookRepository
import com.yusp75.myexam.com.yusp75.myexam.di.PrefManager
import com.yusp75.myexam.data.BookDao
import com.yusp75.myexam.data.ExerciseRecordDao
import com.yusp75.myexam.data.ExerciseStatistics
import com.yusp75.myexam.data.QuestionDao
import com.yusp75.myexam.di.DataHolder

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch


class HomeViewModel(
    bookDao: BookDao,
    questionDao: QuestionDao,
    recordDao: ExerciseRecordDao,
    private val prefManager: PrefManager,
    // koin scope
    private val holder: DataHolder
) : ViewModel() {

    private val repository = BookRepository(bookDao)

    // 当前题库
    private val _currentBook = MutableStateFlow("")
    val currentBook: StateFlow<String> = _currentBook.asStateFlow()

    // 题目总数
    private val _totalCount: Flow<QuestionDao.QuestionTypeCount> =
        questionDao.getQuestionCountFlow()
            .catch { emit(QuestionDao.QuestionTypeCount(0, 0, 0)) } // 拦截异常并返回默认值
            .distinctUntilChanged()
    val totalCount: Flow<QuestionDao.QuestionTypeCount> = _totalCount

    init {
        viewModelScope.launch {
            repository.selectedBook.collect { book ->
                _currentBook.value = book?.name ?: "未选择"
                holder.bookId = book?.id ?: -1
            }
        }

        viewModelScope.launch {
            _totalCount
                .onEach { count ->
                    Log.d(
                        "统计",
                        "题目统计更新: 总数=${count.total} 选择=${count.choiceCount} 判断=${count.judgeCount}"
                    )
                    with(holder) {
                        totalQuestionNum = count.total
                        choiceQuestionNum = count.choiceCount
                        judgeQuestionNum = count.judgeCount
                    }
                }
                .catch { e ->
                    Log.e("统计", e.toString())
                    // 可选: 在这里处理错误或恢复逻辑
                }
                .launchIn(this) // 使用launchIn替代collect
        }
        //
    }

    private val _statistic: Flow<ExerciseStatistics> = recordDao.getQuestionTypeStatistics()
        .catch {
            emit(
                ExerciseStatistics(
                    "异常状态", 0, 0, 0, 0, 0
                )
            )
        } // 拦截所有异常
        .map { stats ->
            if (stats.total == 0) stats.copy(questionType = "无记录")
            else stats
        } // 空结果语义化

    val statistic: Flow<ExerciseStatistics> = _statistic

    // 做题顺序
    val exerciseOrder = MutableLiveData<Int>().apply {
        // 0=顺序,1=随机
        value = prefManager.exerciseOrder
    }

    fun saveOrder(mode: Int) {
        exerciseOrder.value = mode
        prefManager.exerciseOrder = mode
    }

    // 做题范围
    val exerciseScope = MutableLiveData<Int>().apply {
        // 0=顺序,1=随机
        value = prefManager.exerciseScope
    }

    fun saveScope(mode: Int) {
        exerciseScope.value = mode
        prefManager.exerciseScope = mode
    }

    // 做题类型
    val questionType = MutableLiveData<Int>().apply {
        // 0=全部, 1=顺序, 2=随机
        value = prefManager.questionType
    }

    fun saveType(mode: Int) {
        questionType.value = mode
        prefManager.questionType = mode
    }


    override fun onCleared() {
        super.onCleared()
        // 确保资源释放
        repository.clear()
    }
}